package com.zjitc.service.impl;

import com.zjitc.entity.Product;
import com.zjitc.mapper.ProductMapper;
import com.zjitc.service.ProductService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author:徐莹
 * @Date:2025/04/13 11:21:25
 */
@Service
public class ProductServiceImpl implements ProductService {
    
    private static final Logger logger = LoggerFactory.getLogger(ProductServiceImpl.class);
    
    @Autowired
    private ProductMapper productMapper;

    /**
     * 查询商品，先查询二级缓存，缓存未命中则查询数据库并缓存结果
     */
    @Cacheable(value = "product", key = "'product'+#id", unless = "#result == null")
    @Override
    public Product findProductById(Integer id) {
        logger.info("从数据库中查询商品，id={}, 二级缓存未命中", id);
        return productMapper.selectById(id);
    }

    /**
     * 添加商品，更新缓存
     */
    @CachePut(value = "product", key = "'product'+#product.id")
    @Override
    public Product addProduct(Product product) {
        logger.info("添加商品到数据库并更新缓存, product={}", product);
        productMapper.insert(product);
        // 更新商品列表缓存
        refreshProductListCache();
        return product;
    }
    
    /**
     * 更新商品，同时更新缓存
     */
    @CachePut(value = "product", key = "'product'+#product.id")
    @Override
    public Product updateProduct(Product product) {
        logger.info("更新商品并刷新缓存, product={}", product);
        productMapper.updateById(product);
        // 更新商品列表缓存
        refreshProductListCache();
        return product;
    }
    
    /**
     * 删除商品，同时清除缓存
     */
    @CacheEvict(value = "product", key = "'product'+#id")
    @Override
    public void deleteProduct(Integer id) {
        logger.info("删除商品并清除缓存, id={}", id);
        productMapper.deleteById(id);
        // 更新商品列表缓存
        refreshProductListCache();
    }
    
    /**
     * 查询所有商品，使用带版本号的缓存键
     */
    @Cacheable(value = "product", key = "'productList'")
    @Override
    public List<Product> findAllProducts() {
        logger.info("从数据库查询所有商品列表，缓存未命中");
        return productMapper.selectList(null);
    }
    
    /**
     * 刷新商品列表缓存
     * 每次修改商品数据时调用此方法更新列表缓存
     */
    @CacheEvict(value = "product", key = "'productList'", beforeInvocation = true)
    @CachePut(value = "product", key = "'productList'")
    public List<Product> refreshProductListCache() {
        logger.info("刷新商品列表缓存");
        return productMapper.selectList(null);
    }
}
